Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

Lists

Sorting List items

Lists in Python can be sorted to arrange elements in a specific order. Here's a breakdown of the different sorting methods and their functionalities:

1. sort() Method for In-Place Sorting

The built-in sort() method sorts the elements of a list in ascending order by default. It modifies the original list in-place.
Sorting list using sort() method in python numbers = [30, 10, 20, 40] numbers.sort() print(numbers)

Output

[10, 20, 30, 40]

2. Sorting in Descending Order

To sort in descending order, set the reverse parameter of sort() to True.
Sorting list in descending order in python numbers = [30, 10, 20, 40] numbers.sort(reverse=True) print(numbers)

Output

[40, 30, 20, 10]

3. Custom Sorting with a key Function The sort() method allows you to define a custom sorting logic using a key function. This function takes an element as input and returns a value used for comparison during sorting.
Sorting list items by item length in python fruits = ["banana", "pineapple", "cherry", "apple"] def sort_by_length(fruit): return len(fruit) # Sort based on fruit length fruits.sort(key=sort_by_length) print(fruits)

Output

['apple', 'banana', 'cherry', 'pineapple']

4. List Comprehensions for Sorted Results

While not strictly a sorting method, list comprehensions can be used to create a new list with elements sorted based on a condition.
List comprehensions to sort elements in python numbers = [3, 1, 4, 5, 2] sorted_numbers = [number for number in sorted(numbers)] print(sorted_numbers)

Output

[1, 2, 3, 4, 5]

5. Stable Sorting (Preserving Order of Duplicates)

Python's sort() method is considered stable, meaning it preserves the original order of elements with equal values during sorting.
Sorting list with duplicates using sort() method in python numbers = [3, 1, 1, 4, 5] numbers.sort() print(numbers)

Output

[1, 1, 3, 4, 5]

Choosing the Right Method -> Simple ascending or descending order: Use the basic sort() method. -> Custom sorting logic: Employ a custom key function with sort(). -> Creating a new sorted list: Utilize list comprehensions (often more concise). -> When sorting elements with duplicates and preserving their original order, sort() is suitable due to its stable sorting behavior.

  📌TAGS

★python ★ list ★ methods

Tutorials